﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OConf.Common;
using OConf.Service;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace OConf.API.hub
{
    public class ChatHub : Hub
    {
        private readonly IConfiguration _configuration;
        private readonly ProjectInfoService _projectInfoService;
        public ChatHub(IConfiguration configuration)
        {
            _configuration = configuration;
            _projectInfoService = new ProjectInfoService(configuration);
        }

        /// <summary>
        /// 创建SignalR长连接
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
            try
            {
                string appId = Context.GetHttpContext()?.Request.Query["AppId"];
                if (string.IsNullOrEmpty(appId))
                {
                    base.Context.Abort();
                }

                var project = _projectInfoService.FindEnityByProgramName(appId);
                if (project == null || project.IsDelete)
                {
                    base.Context.Abort();
                }
                if (project.IsProtect)
                {
                    string sign = Context.GetHttpContext()?.Request.Query["Sign"];
                    if (string.IsNullOrEmpty(sign))
                    {
                        base.Context.Abort();
                    }

                    SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
                    dic.TryAdd("ProgramName", appId);
                    dic.TryAdd("Key", project.SecretKey);

                    string sign1 = JsonConvert.SerializeObject(dic).MD5Encrypt();
                    if (sign != sign1)
                    {
                        base.Context.Abort();
                    }
                }

                await base.OnConnectedAsync();
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExceptionLog("创建SignalR长连接异常", ex);
                base.Context.Abort();
            }
        }

        /// <summary>
        /// 断开连接事件
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception exception)
        {
            return base.OnDisconnectedAsync(exception);
        }
    }
}